<?php 
/**
 *  Por Federico Pisarello - SisDev Software (c) 2012 - Buenos Aires, Argentina.
 * 	fpisarello@sisdevsoft.com
 */

require("includes/funciones.inc.php");

session_start();
if(!isset($_SESSION['userName']))
	exit();

function searchABMRecipes()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	require("includes/datatables_db/Datatables.php");
	
	$datatables = new Datatables();
	
	$datatables
			->select('idRecipe, description, lastUpdate')
			->edit_column('lastUpdate','$1','desempaquetarFecha(lastUpdate)') // php functions
			->from('recipes')
			->join('restaurant','recipes.idRestaurant = restaurant.idRestaurant')
			->select('businessName')
			->where("recipes.state <> '".$stateErase."'");
	
	if(isset($_REQUEST['sSearchTop']))
	{
		$datatables->where("LEFT(recipes.description,1) = '".$_REQUEST['sSearchTop']."'");
		if($_SESSION['userType'] != $idTypeAdministrator)
			$datatables->where(" AND recipes.idRestaurant = ".$_SESSION['userRestaurant']);
	}
		
	else {
		if($_SESSION['userType'] != $idTypeAdministrator)
			$datatables->where("recipes.idRestaurant = ".$_SESSION['userRestaurant']);
	}

	return $datatables->generate();
}

function addOrEdit()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;

	$DB->StartTrans(); // start transaction
	
	if(!isset($_REQUEST["idRecipe"])){
					
		$strSQL = "INSERT INTO recipes ( ";
		$strSQL .= "	description, ";
		$strSQL .= "	lastUpdate, ";
		$strSQL .= "	state, ";
		$strSQL .= "	idRestaurant ";
		$strSQL .= "	) VALUES ( ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["recipesDescription"], "UTF-8")."', ";
		$strSQL .= "	'".empaquetarFecha($_REQUEST["recipesLastUpdate"])."', ";
		$strSQL .= "	'".$stateAdd."', ";
		if($_SESSION['userType'] == $idTypeAdministrator)
			$strSQL .= "	'".$_REQUEST["cmbRestaurant"]."' ";
		else
			$strSQL .= "	'".$_SESSION['userRestaurant']."' ";
		$strSQL .= "	)";
	}
	else{
		$strSQL = "UPDATE recipes SET ";
		$strSQL .= "	description = '".mb_strtoupper($_REQUEST["recipesDescription"], "UTF-8")."', ";
		$strSQL .= "	lastUpdate = ".empaquetarFecha($_REQUEST["recipesLastUpdate"]).", ";
		$strSQL .= "	state = '".$stateModify."', ";
		if($_SESSION['userType'] == $idTypeAdministrator)
			$strSQL .= "	idRestaurant = ".$_REQUEST["cmbRestaurant"];
		else
			$strSQL .= "	idRestaurant = ".$_SESSION['userRestaurant'];
		$strSQL .= " WHERE idRecipe = ". $_REQUEST["idRecipe"];
	}
	
	$DB->Execute($strSQL);
	
	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorGrabar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkGrabar'];
	}	
	return json_encode($arrJSON);
}

function addIngredient()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	if(!isset($_REQUEST["idRecipe"])) {
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorGrabar'];
		return json_encode($arrJSON);
	}
		
	$DB->StartTrans(); // start transaction
	
	$strSQL = "INSERT INTO recipes_items ( ";
	$strSQL .= "	idRecipe, ";
	$strSQL .= "	description, ";
	$strSQL .= "	quantity, ";
	$strSQL .= "	unit ";
	$strSQL .= "	) VALUES ( ";
	$strSQL .= "	".$_REQUEST["idRecipe"].", ";
	$strSQL .= "	'".mb_strtoupper($_REQUEST["itemRescipesDescription"], "UTF-8")."', ";
	$strSQL .= "	".$_REQUEST["itemRescipesQuantity"].", ";
	$strSQL .= "	".$_REQUEST["cmbUnits"];
	$strSQL .= "	)";
	
	$DB->Execute($strSQL);
	
	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorGrabar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->idItem = $DB->Insert_ID();
		$arrJSON->itemDescrip = generateDecription();
	}	
	return json_encode($arrJSON);
}

function generateDecription()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$rsUnit = $DB->Execute("SELECT * FROM units WHERE idUnit = " . $_REQUEST["cmbUnits"]); // execute query
	
	if($_REQUEST["cmbUnits"] == $unitUnit)
		return $_REQUEST["itemRescipesQuantity"].' '.mb_strtoupper($_REQUEST["itemRescipesDescription"], "UTF-8");
	else
		return $_REQUEST["itemRescipesQuantity"].$rsUnit->fields("value").$a_languages['Common.Of'].mb_strtoupper($_REQUEST["itemRescipesDescription"], "UTF-8");
}

function del()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$DB->StartTrans(); // start transaction
	$DB->Execute("UPDATE recipes SET state='$stateErase' WHERE idRecipe=" . $_REQUEST["idRecipe"]); // execute query

	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorEliminar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkEliminar'];
	}	
	return json_encode($arrJSON);
}

function delIngredient()
{
	require("includes/selectLanguage.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$DB->StartTrans(); // start transaction
	$DB->Execute("DELETE FROM recipes_items WHERE idRecipesItem=" . $_REQUEST["idRecipesItem"]); // execute query

	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorEliminar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkEliminar'];
	}	
	return json_encode($arrJSON);
}

function editRecipe()
{
	require("includes/constants.php");
		
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	if($_SESSION['userType'] == $idTypeAdministrator)
		$rsRecipe = $DB->Execute("SELECT * FROM recipes WHERE state <> '$stateErase' AND idRecipe=" . $_REQUEST["idRecipe"]); // execute query
	else
		$rsRecipe = $DB->Execute("SELECT * FROM recipes WHERE state <> '$stateErase' AND idRestaurant = ".$_SESSION['userRestaurant'] ." AND idRecipe=" . $_REQUEST["idRecipe"]); // execute query
						
	if(!$rsRecipe->EOF){
		$joRecipe->data['description'] = $rsRecipe->fields("description");
		$joRecipe->data['lastUpdate'] = desempaquetarFecha($rsRecipe->fields("lastUpdate"));
		$joRecipe->data['idRestaurant'] = $rsRecipe->fields("idRestaurant");
		
		return json_encode($joRecipe->data);
	}
	else
		return json_encode('');
}

function getRestaurants()
{
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$rsRestaurant = $DB->Execute("SELECT * FROM restaurant");
	
	$i=0;
	while(!$rsRestaurant->EOF){
		$arrRestaurant->data[$i]['idRestaurant'] = $rsRestaurant->fields(0);
		$arrRestaurant->data[$i++]['businessName'] = $rsRestaurant->fields(1);
		$rsRestaurant->MoveNext();
	}
	
	return json_encode($arrRestaurant->data);
}

switch($_REQUEST['actionOfForm'])
{
	case "EDIT":
		echo editRecipe();
		break;
	case "DELETE":
		echo del();
		break;
	case "search":
		echo searchABMRecipes();
		break;
	case "addOrEdit":
		echo addOrEdit();
		break;
	case "addIngredient":
		echo addIngredient();
		break;
	case "delIngredient":
		echo delIngredient();
		break;
	case "getRestaurants":
		echo getRestaurants();
		break;
}
?>
